package cn.zhukelili.spark

import kafka.serializer.StringDecoder
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}


/**
  * Spark Streaming对接Kafka的方式二
  */
object KafkaDirectWordCount {
  def main(args: Array[String]): Unit = {

    if (args.length != 2) {
      System.err.println("Usage: KafkaReceiverWordCount <brokers> <topics> ")
      System.exit(1)
    }

    val Array(brokers, topics) = args

    val sparkConf = new SparkConf()
      //.setMaster("local[2]").setAppName("KafkaDirectWordCount")

    val ssc = new StreamingContext(sparkConf, Seconds(5))

    val topicSet = topics.split(",").toSet
    val  kafkaParams = Map[String,String]("metadata.broker.list" -> brokers)


    //TODO... spark streaming如何对接kafka
    val message = KafkaUtils.createDirectStream[String,String,StringDecoder,StringDecoder](
      ssc,kafkaParams,topicSet
    )

    //    TODO... 自己去测试为什么要取第二个值
    message.map(_._2).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_ + _).print()
    ssc.start()
    ssc.awaitTermination()

  }
}
